import time
from PV_Factory import PV_Factory as pf
from os.path import isfile
from config import get_config

if isfile("./config.py"):
    from config import get_config

pv_datas = get_config()["PV"]


def check_ignition():
    # if pf.create_pv(pv_datas["RF_IN1"]).get() == 1:
    #     return (True, 1)
    # if pf.create_pv(pv_datas["RF_IN1"]).get() == 2:
    #     return (True, 2)
    # else:
    #     return (False,)
    if pf.create_pv(pv_datas["启动开关"]).get() == 1:
        RF_IN1_n = pf.create_pv(pv_datas["RF_IN1"]).get()
        RF_IN2_n = pf.create_pv(pv_datas["RF_IN2"]).get()
        RF_IN3_n = pf.create_pv(pv_datas["RF_IN3"]).get()
        RF_IN4_n = pf.create_pv(pv_datas["RF_IN4"]).get()
        time.sleep(0.2)
        RF_IN1_f = pf.create_pv(pv_datas["RF_IN1"]).get()
        RF_IN2_f = pf.create_pv(pv_datas["RF_IN2"]).get()
        RF_IN3_f = pf.create_pv(pv_datas["RF_IN3"]).get()
        RF_IN4_f = pf.create_pv(pv_datas["RF_IN4"]).get()

        if pf.create_pv(pv_datas["Channel"]).get() == 0:
            S11_12 = (10 ** ((RF_IN2_f - 30) / 10)) / (10 ** ((RF_IN1_f - 30) / 10)) - (
                10 ** ((RF_IN2_n - 30) / 10)
            ) / (10 ** ((RF_IN1_n - 30) / 10))
            pf.create_pv(pv_datas["S11_12"]).put(S11_12)
            if S11_12 > pf.create_pv(pv_datas["激励检查点"]).get():
                pf.create_pv(pv_datas["激励状态"]).put(1)
                return (True, 1)
            elif abs(S11_12) < pf.create_pv(pv_datas["激励检查点"]).get():
                pf.create_pv(pv_datas["激励状态"]).put(0)
                return (False,)
        elif pf.create_pv(pv_datas["Channel"]).get() == 1:
            S11_34 = (10 ** ((RF_IN4_f - 30) / 10)) / (10 ** ((RF_IN3_f - 30) / 10)) - (
                10 ** ((RF_IN4_n - 30) / 10)
            ) / (10 ** ((RF_IN3_n - 30) / 10))
            pf.create_pv(pv_datas["S11_34"]).put(S11_34)
            if S11_34 > pf.create_pv(pv_datas["激励检查点"]).get():
                pf.create_pv(pv_datas["激励状态"]).put(2)
                return (True, 2)
            elif abs(S11_34) < pf.create_pv(pv_datas["激励检查点"]).get():
                pf.create_pv(pv_datas["激励状态"]).put(0)
                return (False,)
    else:
        return (False,)


def check_position():

    datas = check_ignition()
    if datas[0]:
        if datas[1] == 1:
            pf.create_pv(pv_datas["清洗上部时间"]).put(
                pf.create_pv(pv_datas["清洗上部时间"]).get()
                + pf.create_pv(pv_datas["当前清洗时间"]).get()
            )
            pf.create_pv(pv_datas["清洗上部次数"]).put(
                pf.create_pv(pv_datas["清洗上部次数"]).get() + 1
            )
        elif datas[1] == 2:
            pf.create_pv(pv_datas["清洗下部时间"]).put(
                pf.create_pv(pv_datas["清洗下部时间"]).get()
                + pf.create_pv(pv_datas["当前清洗时间"]).get()
            )
            pf.create_pv(pv_datas["清洗下部次数"]).put(
                pf.create_pv(pv_datas["清洗下部次数"]).get() + 1
            )
    else:
        print("当前未激励")
